
//地图配置
const mapConfig = {
  PROPL_ZW: {
    url: process.env.VUE_APP_MAPCONFIGURL + "/hgis/ows",
    params: {
      layers: "ktw:PROPL_ZW", //（省级行政区划）
      format: "image/png",
      service: "WMS",
      styles: "HN_SJXZQH_ZW",
      request: "GetMap",
      srs: "EPSG:4490",
      bbox: [
        108.61269276399997,
        18.15920608800002,
        111.27321472900002,
        20.161093111000014
      ],
      width: 800,
      height: 600
    }
  },
  VEGPL_ZW: {
    url: process.env.VUE_APP_MAPCONFIGURL + "/hgis/ows",
    params: {
      layers: "ktw:VEGPL_ZW", //（植被面）
      format: "image/png",
      service: "WMS",
      styles: "HN_VEGPL_ZW",
      request: "GetMap",
      srs: "EPSG:4490",
      bbox: [108.615359996, 18.159381084000074, 111.030457765, 20.102192113],
      width: 800,
      height: 600
    }
  },
  HYDPL_ZW: {
    url: process.env.VUE_APP_MAPCONFIGURL + "/hgis/ows",
    params: {
      layers: "ktw:HYDPL_ZW", //（水系面）
      format: "image/png",
      styles: "HN_HYDPL_ZW",
      service: "WMS",
      request: "GetMap",
      srs: "EPSG:4490",
      bbox: [
        107.32553316000002,
        1.6023420000000215,
        121.49104052899997,
        21.509347741
      ],
      width: 800,
      height: 600
    }
  },
  RESPL_ZW: {
    url: process.env.VUE_APP_MAPCONFIGURL + "/hgis/ows",
    params: {
      layers: "ktw:RESPL_ZW", //（居民地面）
      format: "image/png",
      styles: "HN_RESPL_ZW",
      service: "WMS",
      request: "GetMap",
      srs: "EPSG:4490",
      bbox: [
        108.61325413900005,
        18.164117997000005,
        111.03820465200005,
        20.160544509000033
      ],
      width: 800,
      height: 600
    }
  },
  RAILN_ZW: {
    url: process.env.VUE_APP_MAPCONFIGURL + "/hgis/ows",
    params: {
      layers: "ktw:RAILN_ZW", //（铁路线）
      format: "image/png",
      styles: "HN_RAILN_ZW",
      service: "WMS",
      request: "GetMap",
      srs: "EPSG:4490",
      bbox: [
        108.62736181700001,
        18.29157022999999,
        110.74864161900001,
        20.042134196999996
      ],
      width: 800,
      height: 600
    }
  },
  ROALN_ZW: {
    url: process.env.VUE_APP_MAPCONFIGURL + "/hgis/ows",
    params: {
      layers: "ktw:ROALN_ZW", //（道路线）
      format: "image/png",
      styles: "HN_ROALN_ZW",
      service: "WMS",
      request: "GetMap",
      srs: "EPSG:4490",
      bbox: [
        108.61330710700003,
        18.085012000000006,
        111.03906281600001,
        20.204249147999974
      ],
      width: 800,
      height: 600
    }
  },
  PLAPT_ZW: {
    url: process.env.VUE_APP_MAPCONFIGURL + "/hgis/ows",
    params: {
      layers: "ktw:PLAPT_ZW", //（地名地址）
      format: "image/png",
      styles: "HN_PLAPT_ZW",
      service: "WMS",
      request: "GetMap",
      srs: "EPSG:4490",
      bbox: [
        108.61208399999998,
        9.72502128100001,
        114.69088676299998,
        20.16260576000002
      ],
      width: 800,
      height: 600
    }
  }
}

import Map from 'ol/Map';
import View from 'ol/View';
import Feature from 'ol/Feature';
import LayerGroup from "ol/layer/Group";
import TileLayer from "ol/layer/Tile";
import TileWMS from "ol/source/TileWMS";
import VectorSource from "ol/source/Vector";
import vectorLayer from "ol/layer/Vector";
import Vector from "ol/layer/Vector";
import { Point, Polygon, CirCle, LineString } from "ol/geom";
import { OSM } from "ol/source";
import * as olProj from "ol/proj";
import Draw from "ol/interaction/Draw";
import Overlay from "ol/Overlay";
import { transform, toLonLat, fromLonLat } from "ol/proj";
import { toStringHDMS } from "ol/coordinate";
import { Fill, Stroke, Style, Icon, Text } from "ol/style";
export default {
  data() {
    return {
      view: null,
      map: null,
      mncMap: {
        '00': 'yidong',
        '01': 'liantong',
        '03': 'dianxin'
      },
      style: new Style({
        // 设置线颜色\宽度
        stroke: new Stroke({ width: 2, color: "#119aff" }),
        // 图形区域内颜色
        fill: new Fill({ color: "rgba(57,160,255,0.5)" })
      }),
      vectorSource: new VectorSource({ wrapX: false }),
      draw: {},
      vector: {},
      //框选的经纬度
      coordinateList: [],
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.drawMap()
    })
    let doc = document.getElementById('map')
    let mapHeight = window.innerHeight
    doc.style.height = `${mapHeight}px`
    window.onresize = ()=> {
      let winHeight = window.innerHeight
      doc.style.height = `${winHeight}px`
    }
  },
  methods: {
    // 初始化地图
    drawMap() {
      let _this = this, data = []
      for (const key in mapConfig) {
        data.push(new TileLayer({ source: new TileWMS(mapConfig[key]) }))
      }
      _this.view = new View({ projection: "EPSG:4326", center: [110.320042, 20.035132], zoom: 12, minZoom: 6 });
      _this.map = new Map({ target: "map", view: _this.view, layers: data });
      
      if(this.drawBool)_this.loadingMap(data)
    },
    // 添加图层-用于框选区域（金拓维电子地图）
    loadingMap(data) {
      let _that = this;
      this.vector = new Vector({ source: this.vectorSource, style: this.style });
      this.map.addLayer( new LayerGroup({ layers: data }) );
      this.map.addLayer(this.vector);
      this.map.on("click", function(evt) {
        var feature = _that.map.forEachFeatureAtPixel(evt.pixel, function(
          feature
        ) {
          return feature;
        });
        if (feature) {
          //点击轨迹标点
        } else {
          //点击地图
        }
      });
    },
    // 根本数据输出标准轨迹
    drawTaskDetailsDrawer(data) {
      // this.isLoading = false // 隐藏查询提示
      const colors = ['red', 'blue', 'green', 'violet', 'deongaree', 'orange']
      this.getRepeatPointer(data)
      this.map.clearOverlays()
      data.forEach((item, index) => {
        this.drawOverlay(item.list, colors[index])
        // 匹配到的轨迹标注序号
        // if (index !== 0) {
        //   const point = new BMap.Point(item.list[0].longitude, item.list[0].latitude)
        //   const html = `<span class="tip ${colors[index]}">${item.key + 1}号轨迹</span>`
        //   const myCompOverlay = new ComplexCustomOverlay(point, html)
        //   this.map.addOverlay(myCompOverlay)
        // }
      })
      this.panTo(data[data.length - 1].list, 0)
    },
    getRepeatPointer(data) {
      let latitudeLongitude = []
      let isRepeatLaLoList = []
      data.forEach((item, index) => {
        if (index !== 0) {
          item.list.forEach(v => {
            let s = Number(v.latitude) + ',' + Number(v.longitude)
            if (latitudeLongitude.includes(s)) {
              isRepeatLaLoList.push(s)
              return
            }
            latitudeLongitude.push(s)
          })
        }
      })
      let l = []
      let repeatLineList = []
      data.forEach((item, index) => {
        if (index !== 0) {
          item.list.forEach((v, i2) => {
            v.listIndex = index
            let s = Number(v.latitude) + ',' + Number(v.longitude)
            if (isRepeatLaLoList.includes(s)) {
              let i = isRepeatLaLoList.indexOf(s)
              let time = new Date(v.arriveTime).Format('yyyy-MM-dd hh:mm:ss')
              v.isRepeat = true
              if (l.map(v1 => v1.index).includes(i)) {
                let y = l.map(v2 => v2.index).indexOf(i)
                // v.text = l[y].text + `\n【${i2 + 1}】${v.phone} ${index}号轨迹点 经过时间 ${time}`
                v.text = l[y].text + `\n ${v.phone} ${index}号轨迹点 经过时间 ${time}`
                v.index = l[y].index
                v.flag = v.flag || l[y].flag
                if (v.listIndex !== l[y].listIndex) {
                  v.repeatLine = true
                  repeatLineList.push(s)
                }
                l[y] = Object.assign({}, v)
                return
              }
              l.push({
                index: i,
                text: ` ${v.phone}  ${index}号轨迹点 经过时间 ${time}`,
                flag: v.flag,
                listIndex: v.listIndex
              })
              v.text = ` ${v.phone}  ${index}号轨迹点 经过时间 ${time}`
            }
          })
        }
      })
      data.forEach((item, index) => {
        if (index !== 0) {
          item.list.forEach(v => {
            let s = Number(v.latitude) + ',' + Number(v.longitude)
            if (repeatLineList.includes(s)) {
              v.repeatLine = true
            }
          })
        }
      })
    },
    drawOverlay(data, type) {
      this.addLine(data, type)
      this.addMarker(data, type)
    },
    addLine(data, type) {
      const colors = {
        red: '#d91f1b',
        blue: '#009dd9',
        // blue: "#2F98F4",
        green: '#48bb00',
        violet: '#762bd0',
        deongaree: '#1921b3',
        orange: 'orange'
      }
      let line = []
      data.forEach((item, index) => {
        line.push(new BMap.Point(item.longitude, item.latitude))
      })
      var polyline = new BMap.Polyline(line, {
        strokeColor: colors[type],
        strokeWeight: 2.5,
        strokeOpacity: 0.8
      }) // 创建折线
      this.map.addOverlay(polyline) // 增加折线
    },
    addMarker(data, type) {
      data.forEach((item, index) => {
        const mnc = this.mncMap[item.mnc]
        const point = new BMap.Point(item.longitude, item.latitude)
        // const html = `<span class="sign ${item.flag ? 'orange' : type}" style="background-image: url("../../assets/images/${mnc}_${type}.png")">${index + 1}</span>`
        let html = `<span class="index${index} sign${mnc ? '' : ' red'} ${
          item.elapsedEndTime ? type : !item.flag ? mnc + '_black' : mnc + '_' + type
        }"></span><span class="sign_text ${type}_color">${index + 1}</span>`
        if (item.repeatLine) {
          html = `<span class="saojiao"></span>`
        }
        // console.log(html)
        // html += item.repeatLine ? `<span class="saojiao" longitude=${item.longitude} latitude=${item.latitude} text='${item.text}'></span>` : ''
        const myCompOverlay = new ComplexCustomOverlay(point, html)
        let marker = new BMap.Marker(point)
        this.map.addOverlay(marker)
        this.map.addOverlay(myCompOverlay)
        let label
        if (item.alarmTime) {
          label = new BMap.Label(
            '<div class="markerTipBox">' +
              '<p>序号：' +
              (item.key + 1) +
              '</p>' +
              '<p>姓名/代号：' +
              item.codeName +
              '</p>' +
              '<p>手机号码：' +
              item.phone +
              '</p>' +
              '<p>出现时间：' +
              item.alarmTime +
              '</p></div>',
            {
              offset: new BMap.Size(20, -110)
            }
          )
        } else if (item.position) {
          //人物画像(职住区域)
          label = new BMap.Label(
            '<div class="markerTipBox"><p>' +
              '序号:' +
              (item.key + 1) +
              '</p><p>' +
              '位置:' +
              item.position +
              '</p><p>' +
              '经度:' +
              item.longitude +
              '</p><p>' +
              '纬度:' +
              item.latitude,
            {
              offset: new BMap.Size(20, -110)
            }
          )
        } else if (item.appearTime) {
          //最新位置，历史轨迹，密文情报
          label = new BMap.Label(
            '<div class="markerTipBox"><p>' +
              '序号:' +
              (item.key + 1) +
              '</p><p>' +
              '时间：' +
              item.appearTime +
              '</p><p>' +
              '位置：' +
              item.address +
              '</p><p>' +
              '经度：' +
              item.longitude +
              '</p><p>' +
              '纬度：' +
              item.latitude,
            {
              offset: new BMap.Size(20, -110)
            }
          )
        } else {
          //默认
          label = new BMap.Label(
            '<div class="markerTipBox"><p>' +
              '序号:' +
              (item.key + 1) +
              '</p><p>' +
              '经度:' +
              item.longitude +
              '</p><p>' +
              '纬度:' +
              item.latitude,
            {
              offset: new BMap.Size(20, -110)
            }
          )
        }
        marker.setLabel(label)
        // pointArray[i] = new BMap.Point(points[i].lon, points[i].lat);
        // 初始化不显示
        label.setStyle({
          display: 'none'
        })
        // 鼠标经过时
        marker.addEventListener('mouseover', function(e) {
          var label = this.getLabel()
          label.setStyle({
            display: 'block'
          })
        })
        // 鼠标离开时
        marker.addEventListener('mouseout', function(e) {
          var label = this.getLabel()
          label.setStyle({
            display: 'none'
          })
        })
      })
    },
    panTo(data, key) {
      const target = data.filter(item => key === item.key)[0]
      target && this.map.panTo(new BMap.Point(target.longitude, target.latitude))
    },
    //-----------------框选区域操作------------------
    //框选多边形
    drawPolygon() {
      const that = this;
      this.clearLayer();
      this.draw = new Draw({ type: "Polygon", source: this.vectorSource, free: false });
      this.map.addInteraction(this.draw);
      this.draw.on(
        "drawend",
        evt => {
          if (evt.feature != null) {
            //通过改变onTool的值间接触发removeInteraction函数 可以结束绘制
            // this.onTool = 'none'
            this.removeDraw();
            // 绘制结束之后 绘制出的点线面数据
            that.coordinateList = evt.feature
              .getGeometry()
              .getFlatCoordinates();
            console.log(that.coordinateList, that.group(that.coordinateList, 2));
            this.$emit('change', that.group(that.coordinateList, 2))
            // console.log(evt.feature.getGeometry().getCoordinates());
          }
        },
        this
      );
    },
    //框选圆形
    drawCircle() {
      const that = this;
      this.clearLayer();
      this.draw = new Draw({ type: "Circle", source: this.vectorSource, free: false });
      this.map.addInteraction(this.draw);
      this.draw.on(
        "drawend",
        evt => {
          if (evt.feature != null) {
            //通过改变onTool的值间接触发removeInteraction函数 可以结束绘制
            // this.onTool = 'none'
            this.removeDraw();
            // 绘制结束之后 绘制出的点线面数据
            // evt.feature.getGeometry().getFlatCoordinates() = []
            // var
            console.log(
              evt.feature.getGeometry().getCenter(),
              evt.feature.getGeometry().getRadius()
            );

            var a = evt.feature.getGeometry().getCenter();
            var b = evt.feature.getGeometry().getRadius();
            that.coordinateList = [a[0], a[1], b];
            console.log(that.coordinateList);
            this.$emit('change', that.coordinateList)
            // 圆心的框选的时候获取到坐标：evt.feature.getGeometry().getCenter()  跟半径 evt.feature.getGeometry().getRadius()
            // console.log(evt.feature.getGeometry().getFlatCoordinates());
          }
        },
        this
      );
    },
    //编辑时-绘制区域
    drawPolygonEdit(arr) {
      console.log('Edit',arr)
      // if(this.coordinateList.length>0) return
      let vectorSource = new VectorSource();
      // var coordinatesPolygon = [[110.33762012919095, 20.0428224180969], [110.34283863924128, 20.029638831681066], [110.32059131850173, 20.027990886653267]];
      //循环遍历将经纬度转到"EPSG:4326"投影坐标系下
      // for (var i = 0; i < this.coordinatesData.length; i++) {
      //   var pointTransform = fromLonLat([this.coordinatesData[i][0], this.coordinatesData[i][1]], "EPSG:4326");
      //   coordinatesPolygon.push(pointTransform);
      // }
      var feature = "";
      if (arr.length == 2) {
        // 圆形
        feature = new Feature({ geometry: new Circle([arr]) });
      } else {
        //多边形要素类
        feature = new Feature({ geometry: new Polygon([arr]) });
      }

      var styles = [
        new Style({ stroke: new Stroke({ color: "red", width: 1 }), fill: new Fill({ color: "rgba(255,188,206,0.5)" }) })
      ];
      //添加点样式
      feature.setStyle(styles);
      vectorSource.addFeature(feature);
      var vectorLayer = new Vector({ title: "equipment", source: vectorSource });
      this.vectorLayer = vectorLayer;
      return vectorLayer;
    },
    //删除绘画笔
    removeDraw() {
      this.map.removeInteraction(this.draw);
    },
    //清除框选
    clearLayer() {
      this.coordinateList = [];
      // this.queryForm.sjskPositionParamVOList = [];
      this.vector.getSource().clear();
      // 删除后端回来绘制的区域
      if (this.map !== null) {
        this.map.removeLayer(this.vectorLayer);
      }
      this.$emit('change', this.coordinateList)
    },
    // 隔数组
    group(array, subGroupLength) {
      let index = 0;
      let newArray = [];
      while (index < array.length) {
        newArray.push(array.slice(index, (index += subGroupLength)));
      }
      return newArray;
    },
    
  },
  model:{
    prop: 'value',
    event: 'change'
  }
}
